﻿@using System.ComponentModel.DataAnnotations
@using Blazor.Localization
@using Blazor.Pages.UpdateSetting.Modals.Whitelist
@using Blazor.Util.Const
@using Blazor.Validators
@inherits Blazor.Core.SoraniFeedbackComponentBase<ChangeNativeVersionOptions, ChangeNativeVersionResult?>
@inject IStringLocalizer<UpdateSettingLocalization> Loc

<Form @ref="_form" Model="_model" LabelColSpan="8" WrapperColSpan="16" LabelAlign="AntLabelAlignType.Left">
    <FormItem Label="@Loc[UpdateSettingLocalization.LatestNativeVersion]">
        <Input @bind-value="@context.LatestNativeVersion"
               Disabled="@((Options.Type & ChangeNativeVersionOptions.EditType.Latest) == 0)"/>
    </FormItem>

    <FormItem Label="@Loc[UpdateSettingLocalization.MinNativeVersion]">
        <Input @bind-value="@context.MinNativeVersion"
               Disabled="@((Options.Type & ChangeNativeVersionOptions.EditType.Min) == 0)"/>
    </FormItem>
</Form>

@code
{
    private class FormData
    {
        [Range(0, 999999, ErrorMessageResourceName = nameof(ValidatorLocalization.InvalidNativeVersion), ErrorMessageResourceType = typeof(ValidatorLocalization))]
        [Comparison(nameof(MinNativeVersion), ComparisonOperator.GreaterThanOrEqual, ErrorMessageResourceName = nameof(ValidatorLocalization.LatestNativeVersionTip), ErrorMessageResourceType = typeof(ValidatorLocalization))]
        public uint LatestNativeVersion { get; set; }

        [Range(0, 999999, ErrorMessageResourceName = nameof(ValidatorLocalization.InvalidNativeVersion), ErrorMessageResourceType = typeof(ValidatorLocalization))]
        [Comparison(nameof(LatestNativeVersion), ComparisonOperator.LessThanOrEqual, ErrorMessageResourceName = nameof(ValidatorLocalization.MinNativeVersionTip), ErrorMessageResourceType = typeof(ValidatorLocalization))]
        public uint MinNativeVersion { get; set; }
    }

    private FormData _model;
    private Form<FormData> _form;

    protected override void OnInitialized()
    {
        _model = new FormData()
        {
            LatestNativeVersion = Options.LatestNativeVersion,
            MinNativeVersion = Options.MinNativeVersion,
        };

        base.OnInitialized();
    }

    public override Task OnFeedbackOkAsync(ModalClosingEventArgs args)
    {
        if (!_form.Validate())
        {
            args.Reject();
            return Task.CompletedTask;
        }

        var result = new ChangeNativeVersionResult()
        {
            Latest = _model.LatestNativeVersion,
            Min = _model.MinNativeVersion,
        };
        OkCancelRefWithResult.OkAsync(result);

        return Task.CompletedTask;
    }
}
